package com.lepu.app.fun.mother_circle.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.adapter.MessageListAdapter;
import com.lepu.app.fun.mother_circle.bean.BeanMotherMessage;
import com.lepu.app.main.activity.MainTabActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * MotherEventFragment
 */
public class MotherMessageFragment extends BaseFragment implements AsyncRequest {
    private View mMainView = null;
    private boolean mInitDataSuccess = false;//是否加载完数据
    @SuppressWarnings("unused")
	private ListView mDataListView;
    @SuppressWarnings("unused")
	private MessageListAdapter mAdapter;
    private static final String REQUEST_DATA = "request_data";
    private static final String EVENTID = "eventId";

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMainView = LayoutInflater.from(getActivity()).inflate(
                R.layout.mother_layout_list, null, false);
        init();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        ViewGroup p = (ViewGroup) mMainView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mMainView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mInitDataSuccess = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess) {
                // 第一次进入页面获取数据
                mInitDataSuccess = true;
                initData();
            }
        }
    }


    /*
     * 初始化ui控件，不要初始化数据！！！！
     *
     * 初始化控件，需要用mMainView.findViewById
     * 不能使用findViewById，否则程序会闪退的
     */
    private void init() {
//        mDataListView = (ListView) mMainView.findViewById(R.id.two_listview);
//        mAdapter = new MessageListAdapter(getActivity(), null);
//        mDataListView.setAdapter(mAdapter);
        initData();
    }

    public void initData() {
        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);
            params.put("UserID",LoginUtil.getUserId()) ;
            params.put("LoginToken",  LoginUtil.getLoginToken());
            String time = getRefreshTime();
            params.put("LastUpdateTime", time);
        } catch (Exception e) {
        }
        map.put("ht", params);

        MainTabActivity.getInstance().showProgressDialog();
        ApiClient.http_post_main(Setting.getNewInnerMessageList(), map, null, this,
                REQUEST_DATA, true);
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_DATA)) {
            // 解析json data
            //todo {"Result":{"Status":"200","Message":"获取消息列表成功","Type":"List","ListInfo":[],"DetailInfo":{"CurrentTime":"2015-12-05 13:41:25"}}}
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(data.toString());
                JSONObject obj1 = (JSONObject) jsonObject.get("Result");
                JSONObject detailInfo = (JSONObject) obj1.optJSONObject("DetailInfo");
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String time = format.format(new Date());
                String lastTime = detailInfo == null ? time : detailInfo.optString("CurrentTime");
                ArrayList<BeanMotherMessage> dataList = BeanMotherMessage.getDataList(obj1);
                UserConfig.setConfig(MyApplication.getInstance(), EVENTID + LoginUtil.getUserId(), lastTime);
                mInitDataSuccess = true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private String getRefreshTime() {
        String time = "";
        String messageId = UserConfig.getConfigString(MyApplication.getInstance(), EVENTID + LoginUtil.getUserId(), "");
        if (TextUtils.isEmpty(messageId)) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            time = format.format(new Date());
        } else {
            time = messageId;
        }
        return time;
    }

    @Override
    public void RequestError(Object o, int i, String s) {
        MainTabActivity.getInstance().hideProgressDialog();
    }
}
